package com.ruoyi.tzai.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.tzai.domain.AIModelConfig;
import com.ruoyi.tzai.service.IAIModelConfigService;
import com.ruoyi.tzai.service.ai.AIServiceFactory;
import com.ruoyi.tzai.service.ai.IAIService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * AI服务测试控制器
 */
@Api(tags = "AI服务测试")
@RestController
@RequestMapping("/test/ai")
public class TestAIController extends BaseController {
    
    private static final Logger log = LoggerFactory.getLogger(TestAIController.class);
    
    @Autowired
    private AIServiceFactory aiServiceFactory;
    
    @Autowired
    private IAIModelConfigService aiModelConfigService;
    
    /**
     * 测试默认AI服务
     */
    @ApiOperation("测试默认AI服务")
    @GetMapping("/default")
    public AjaxResult testDefaultService() {
        try {
            log.info("=== 开始测试默认AI服务 ===");
            
            // 1. 获取默认配置
            AIModelConfig config = aiModelConfigService.selectDefaultAIModelConfig();
            if (config == null) {
                return error("未找到默认AI模型配置");
            }
            log.info("默认AI模型配置: ID={}, 名称={}, 提供商={}", 
                config.getModelId(), config.getModelName(), config.getProvider());
            
            // 2. 获取AI服务
            log.info("准备获取默认AI服务...");
            IAIService service = aiServiceFactory.getDefaultService();
            
            if (service == null) {
                log.error("获取默认AI服务失败，返回null");
                return error("获取默认AI服务失败");
            }
            
            log.info("AI服务获取成功: {}", service.getModelName());
            
            // 3. 测试连接
            log.info("测试AI服务连接...");
            boolean connected = service.testConnection();
            log.info("连接测试结果: {}", connected);
            
            return success("测试成功，模型: " + service.getModelName() + ", 连接: " + connected);
            
        } catch (Throwable e) {
            log.error("测试AI服务时发生异常", e);
            return error("测试失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试生成摘要
     */
    @ApiOperation("测试生成摘要")
    @GetMapping("/summary")
    public AjaxResult testSummary() {
        try {
            IAIService service = aiServiceFactory.getDefaultService();
            if (service == null) {
                return error("无法获取AI服务");
            }
            
            String content = "这是一个测试内容，用于测试AI摘要生成功能。";
            String summary = service.generateSummary(content, "cn");
            
            return success("摘要生成成功").put("summary", summary);
            
        } catch (Exception e) {
            log.error("测试摘要生成失败", e);
            return error("测试失败: " + e.getMessage());
        }
    }
}

